import axios from 'axios';
import store from '@/store';
import { getToken, getClient, setClient } from '@/utils/auth';
import { baseURL } from '@/settings.js';
import { Notification } from 'element-ui';
import error_image from '@/assets/images/Aowa_1.jpg';

if (!getClient()) {
  setClient();
}

const service = axios.create({
  baseURL: baseURL.KujoMiva,
  timeout: 500000,
  validateStatus: status => status < 500
});

service.interceptors.request.use(
  config => {
    config.headers['client'] = getClient();
    if (store.getters.token) {
      config.headers['authorization'] = 'Bearer ' + getToken();
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code >= 400) {
      Notification({
        position: 'bottom-right',
        dangerouslyUseHTMLString: true,
        message: `<img style=width:100% src="${error_image}"> <div>${res.message}! (｀・ω・´)<div/>`
      });
    }
    return res;
  },
  error => {
    Notification({
      position: 'bottom-right',
      dangerouslyUseHTMLString: true,
      message: `<img style=width:100% src="${error_image}"> <div>服务器出错了! (｀・ω・´)<div/>`
    });
    return Promise.reject(error);
  }
);

export default service;
